var marketViewModel;

$(document).ready(function() {
	marketViewModel = new marketViewModel(marketDto, isOwner);
	ko.applyBindings(marketViewModel, $("#productDetail-container")[0]);
});

function marketViewModel(market, isOwner) {
	var self = this;
	
	self.id = market["id"];
	self.name = market["name"];
	self.subtitle = market["subtitle"];
	self.description = market["description"];
	
	self.environmentAffect = market["environmentAffect"];
	self.qualityImprovement = market["qualityImprovement"];
	self.organization = market["organization"];
	self.recognitionReceived = market["recognitionReceived"];
	
	self.imageUrl = getImagePath('image/marketThumb', market["imagePath"], "medium");
	self.fancyImageUrl = getImagePath('image/marketThumb', market["imagePath"], "large");
	self.isOwner = isOwner;
	self.visibleMap = market.latitude != undefined && market.longitude != undefined;
	
	self.products = ko.observableArray();
	
	self.getProductsSuccess = function(products) {
		self.products($.map(products.elements, function (product) { return new Product(product, isOwner); }));
	};
	
	self.showProducts = function(products) {
		$(products).show();
	};
	
	self.setMap = function(){
		var lat = market && market.latitude ? market.latitude : -34.6028;
		var lng = market && market.longitude ? market.longitude : -58.3816;
		var latlng = new google.maps.LatLng(lat, lng);
		var mapOptions = {
			center: latlng,
			zoom: 15,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
	    new google.maps.Marker({
	        map: map, 
	        position: latlng
	    });
	};
	
	getService("market/getMarketById", { "marketId" : self.id }, self.getMarketSuccess);
	self.pager = ko.observable(new Pager({ webService: "product/getProductsByMarketId", params : { "marketId" : self.id, "pageSize" : 8 }, onSuccess: self.getProductsSuccess }));
	
	self.setMap();
}